package com.taxi.driver.module.login;

import android.content.Context;
import android.content.Intent;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatButton;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qianxx.utils.PhoneUtils;
import com.taxi.driver.R;
import com.taxi.driver.common.AppConfig;
import com.taxi.driver.common.BaseFragment;
import com.taxi.driver.module.account.identity.IdentityActivity;
import com.taxi.driver.module.login.dagger.DaggerLoginComponent;
import com.taxi.driver.module.login.dagger.LoginModule;
import com.taxi.driver.module.main.MainActivity;
import com.taxi.driver.module.web.WebActivity;
import com.taxi.driver.util.SpaceFilter;
import com.taxi.driver.widget.dialog.TwoSelectorDialog;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 功能描述：
 */
public class LoginFragment extends BaseFragment implements LoginContract.View {

    public static LoginFragment newInstance() {
        return new LoginFragment();
    }

    @BindView(R.id.et_login_phone)
    EditText mEtLoginPhone;
    @BindView(R.id.et_login_pwd)
    EditText mEtLoginPwd;
    @BindView(R.id.iv_switch)
    ImageView mIvSwitch;
    @BindView(R.id.btn_login)
    AppCompatButton mBtnLogin;
    @BindView(R.id.tv_register)
    TextView mTvRegister;
    @BindView(R.id.ll_agress)
    LinearLayout mLlAgress;
    @BindView(R.id.keyboard_view)
    KeyboardView mKeyboardView;

    @Inject
    LoginPresenter mPresenter;

    boolean isFirstComeIn = true;
//    String mCurrentCity;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_login, container, false);
        ButterKnife.bind(this, mView);
        mPresenter.onCreate();
//        mEtLoginPhone.setTextColor(Color.BLACK);
        if (!TextUtils.isEmpty(mPresenter.getAccount())) {
            mEtLoginPhone.setText(mPresenter.getAccount());
            Selection.setSelection(mEtLoginPhone.getEditableText(), mEtLoginPhone.getEditableText().length());
        }

        mEtLoginPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 11) {
                    mEtLoginPwd.requestFocus(); //焦点切换到下一个输入框

                    if (mEtLoginPwd.getEditableText().length() >= 6)
                        mBtnLogin.setEnabled(true); //输入满足条件，启用登录键

                } else {
                    mBtnLogin.setEnabled(false); //输入未满足条件，禁用登录键
                }
            }
        });
        mEtLoginPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() >= 6) {
                    if (mEtLoginPhone.getEditableText().length() == 11)
                        mBtnLogin.setEnabled(true); //输入满足条件，启用登录键
                } else {
                    mBtnLogin.setEnabled(false); //输入未满足条件，禁用登录键
                }
            }
        });
        mEtLoginPwd.setFilters(new InputFilter[]{new SpaceFilter(getActivity())});

        return mView;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isFirstComeIn) {
            isFirstComeIn = false;
            return;
        }
        if (mEtLoginPhone.getText().toString().length() > 0)
            mEtLoginPhone.requestFocus(mEtLoginPhone.getText().toString().length());
        else
            mEtLoginPhone.requestFocus();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        DaggerLoginComponent.builder()
                .appComponent(getAppComponent())
                .loginModule(new LoginModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mPresenter.onDestory();
    }

    @OnClick({R.id.img_head_left, R.id.tv_login_forget,
            R.id.btn_login, R.id.iv_switch, R.id.tv_register,
            R.id.ll_agress})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_head_left:
                getActivity().finish();
                break;
            case R.id.tv_login_forget:
                IdentityActivity.actionStart(getContext(),
                        mEtLoginPhone.getEditableText().toString().trim(),
                        false);
                break;
            case R.id.btn_login:
                mPresenter.reqLogin(mEtLoginPhone.getEditableText().toString().trim(),
                        mEtLoginPwd.getEditableText().toString().trim(),
                        true);
                break;
            case R.id.iv_switch:
                boolean showPwd = !mIvSwitch.isSelected();
                mIvSwitch.setSelected(showPwd);
                changPwdDisplay(showPwd);
                break;
            case R.id.tv_register://司机招募
//                Navigate.openDriverCruiteActivity(getActivity());
                String url = AppConfig.HOST + "/h5/driver/register.yueyue" +
                        "?appid=" + AppConfig.YUEYUE_APPKEY +
                        "&type=" + AppConfig.getCarType();
                WebActivity.actionStart(getContext(), url, "司机申请");
//                if (BuildConfig.FLAVOR_type.contains("taxi")) {
//                    String url = AppConfig.HOST + "/h5/taxiDriver/register.yueyue" +
//                            "?appid=" + AppConfig.YUEYUE_APPKEY +
//                            "&type=" + AppConfig.getCarType();
//                    WebActivity.actionStart(getContext(), url, "司机申请");
//                } else {
//                    String url = AppConfig.HOST + "/h5/driver/register.yueyue" +
//                            "?appid=" + AppConfig.YUEYUE_APPKEY +
//                            "&type=" + AppConfig.getCarType();
//                    WebActivity.actionStart(getContext(), url, "司机申请");
//                }
                break;
            case R.id.ll_agress:
                mPresenter.getConfig();
                break;
        }
    }


//    @Override
//    public void getCurrentCity(String city) {
//        mCurrentCity=city;
//    }

    @Override
    public void loginIsFirst(String phone) {
        /* 首次登录，需要修改密码 */
        IdentityActivity.actionStart(getContext(), phone, true);
    }

    @Override
    public void loginSuccess() {
        startActivity(new Intent(getContext(), MainActivity.class));
        getActivity().finish();
    }

    @Override
    public void loginFail(int errCode, String errMsg) {
        // TODO 处理相应的错误码
    }

    @Override
    public void changPwdDisplay(boolean showPwd) {
        if (showPwd) {
            mEtLoginPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            mEtLoginPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
        Selection.setSelection(mEtLoginPwd.getEditableText(), mEtLoginPwd.getEditableText().length());
    }

    @Override
    public void clearPwd() { //清除密码
        mEtLoginPwd.getEditableText().clear();
    }

    @Override
    public void showAccountUnavailable(String reason) {
//        mPresenter.getCurrentCity();
        if (TextUtils.isEmpty(reason)) reason = "您的账号已被封";

        new TwoSelectorDialog(getActivity(), "账号被封", TextUtils.isEmpty(reason) ? null : reason,
                "联系客服", "我知道了")
                .setConfirmClickListener(sweetAlertDialog -> {
                    if (sweetAlertDialog != null)
                        sweetAlertDialog.dismiss();
                }).setCancelClickListener(sweetAlertDialog -> {
                    if (sweetAlertDialog != null)
                        sweetAlertDialog.dismiss();
            PhoneUtils.skip(getContext(), R.string.contact_phone);

//            if (mCurrentCity.equals("天津市")){
//                 PhoneUtils.skip(getContext(), R.string.contact_phone);
//            }else{
//                PhoneUtils.skip(getContext(), R.string.contact_phone_other);
//            }
                }).show();
    }

    @Override
    public void gotoAgree(String url) {
        WebActivity.actionStart(getContext(), AppConfig.HOST + url, "用户协议");
    }
}
